package com.elseyu.osctest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.elseyu.osctest.bean.TweetBean;
import com.elseyu.osctest.osc.ApiConnector;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int PAGE_SIZE = 20;

    private List<TweetBean> mTweetList = new ArrayList<>();
    private ListView mListView;
    private MyAdapter mAdapter = null;
    private int mCurPageIndex = 1;
    private boolean isLoadingMore = false;
    private View mFooter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initImageLoader();
        initData();
        initView();
    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.tweet_list);
        mFooter = LayoutInflater.from(this).inflate(R.layout.list_footer, null, false);

    }

    private void initListView() {
        mAdapter = new MyAdapter();
        mListView.setAdapter(mAdapter);
        mListView.addFooterView(mFooter);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //滑到底部加载更多
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        loadMore();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    private void loadMore() {
        //设置isLoadingMore标志,防止重复触发
        if (!isLoadingMore) {
            isLoadingMore = true;
            Observable.just("")
                    .subscribeOn(Schedulers.io())
                    .map(new Func1<String, List<TweetBean>>() {
                        @Override
                        public List<TweetBean> call(String s) {
                            String res = new ApiConnector().getTweetList(mCurPageIndex + 1,PAGE_SIZE);
                            parseJson(mTweetList,res);
                            return mTweetList;
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext(new Action1<List<TweetBean>>() {
                        @Override
                        public void call(List<TweetBean> tweetList) {
                            mAdapter.notifyDataSetChanged();
                            mCurPageIndex++;
                            isLoadingMore = false;
                        }
                    })
                    .subscribe();
        }
    }

    private void initData() {
        Observable.just("")
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, List<TweetBean>>() {
                    @Override
                    public List<TweetBean> call(String s) {
                        String res = new ApiConnector().getTweetList(mCurPageIndex,PAGE_SIZE);
                        parseJson(mTweetList,res);
                        return mTweetList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<List<TweetBean>>() {
                    @Override
                    public void call(List<TweetBean> tweetList) {
                        //取到数据后刷新listView
                        initListView();
//                        for (TweetBean bean : tweetList) {
//                            Log.d(TAG, "call: " + bean);
//                        }
                    }
                })
                .subscribe();
    }



    private void initImageLoader() {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .memoryCache(new WeakMemoryCache())
                .memoryCacheExtraOptions(1280, 720)
                .threadPoolSize(3)// 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5
                .tasksProcessingOrder(QueueProcessingType.FIFO)
                .diskCacheFileCount(100) //缓存的File数量
                .diskCache(new UnlimitedDiskCache(new File("")))// 自定义缓存路径
                .writeDebugLogs() // Remove for release app
                .build();

        ImageLoader.getInstance().init(config);
    }

    private void parseJson(List<TweetBean> list, String json) {
        if (list == null || json == null || json.isEmpty()) {
            return ;
        }
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray= new JSONArray(jsonObject.optString("tweetlist"));
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject item = jsonArray.optJSONObject(i);
                if (item == null) continue;
                TweetBean tweetBean = new TweetBean();
                tweetBean.setAuthor(item.getString("author"));
                tweetBean.setAuthorid(item.getLong("authorid"));
                tweetBean.setBody(item.getString("body"));
                tweetBean.setCommentCount(item.getInt("commentCount"));
                tweetBean.setPortrait(item.getString("portrait"));
                tweetBean.setPubDate(item.getString("pubDate"));
                list.add(tweetBean);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    class ViewHolder {
        ImageView face;
        TextView name;
        TextView content;
        TextView time;
        TextView commentCount;
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mTweetList.size();
        }

        @Override
        public Object getItem(int i) {
            return mTweetList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int pos, View coverView, ViewGroup viewGroup) {
            TweetBean tweetBean = null;
            if (mTweetList != null) {
                tweetBean = mTweetList.get(pos);
            }
            ViewHolder viewHolder;
            if (coverView == null) {
                coverView = LayoutInflater.from(MainActivity.this).inflate(R.layout.tweet_list_item,null,false);
                viewHolder = new ViewHolder();
                viewHolder.face = (ImageView) coverView.findViewById(R.id.tweet_face);
                viewHolder.name = (TextView) coverView.findViewById(R.id.tweet_name);
                viewHolder.content = (TextView) coverView.findViewById(R.id.tweet_content);
                viewHolder.time = (TextView) coverView.findViewById(R.id.time);
                viewHolder.commentCount = (TextView) coverView.findViewById(R.id.comment_count);
                coverView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) coverView.getTag();
            }
            if (tweetBean != null) {
                viewHolder.name.setText(tweetBean.getAuthor());
                viewHolder.content.setText(tweetBean.getBody());
                viewHolder.time.setText(tweetBean.getPubDate());
                viewHolder.commentCount.setText(tweetBean.getCommentCount() + "");
                ImageLoader.getInstance().displayImage(tweetBean.getPortrait(),viewHolder.face);
            }
            return coverView;
        }
    }
}
